package com.xiao.elasticsearch.controller;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Description ES 相关操作示例控制器
 * @Auther: 笑笑是一个码农
 * @Date: 15:27 2021/1/16
 */
@RestController
@Slf4j
public class ESTestController {

    @Resource(name = "esHighLevelRestClient")
    RestHighLevelClient restHighLevelClient;

    /**
     * 创建索引示例接口
     * @param indexName
     * @return
     */
    @PostMapping(value = "/v1/elasticsearch/index/{indexName}")
    public String createIndex(@PathVariable("indexName") String indexName){
        CreateIndexRequest request = new CreateIndexRequest(indexName);
        try {
            CreateIndexResponse response = this.restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
            return response.toString();
        } catch (IOException e) {
            log.error("[ elasticsearch示例服务 ] 创建索引库异常", e);
            return "创建索引库异常"; // fixme 待全局异常完成后修复
        }
    }
}
